var resultDivId = "mxShanbayResultDiv";
var resultDivClassName = "mxShanbayResultDiv";
var resultDivSelector = "#" + resultDivId;

var WORD_DIV_ID = "wordDiv";
var WORD_DIV_SELECTOR = "#" + WORD_DIV_ID;

var DEFINITION_DIV_ID = "mxShanbayDefinitionDiv";
var DEFINITION_DIV_SELECTOR = "#" + DEFINITION_DIV_ID;

var ADD_WORD_OPERA_DIV_ID = "addworda";
var ADD_WORD_OPERA_SELECTOR = "#" + ADD_WORD_OPERA_DIV_ID;

var ADDED_WORD_SPAN_ID = "addedword";
var ADDED_WORD_SPAN_SELECTOR = "#"+ ADDED_WORD_SPAN_ID;

var PRONUNCIATION_DIV_ID = "sb_pronunciation";
var PRONUNCIATION_DIV_SELECTOR = "#" + PRONUNCIATION_DIV_ID;

var isMouseOnResultDiv = false;
var WORD_QUERY_API = "http://www.shanbay.com/api/word/";
var WORD_ADD_API = "http://www.shanbay.com/api/learning/add/";

var RESULT_DIV_TOP = 0;
var RESULT_DIV_LEFT = 0;

var WORDNOW;
var ISOPEN = true;

var runtime = window.external.mxGetRuntime();


function calculateResultDivSite(event){
		// 计算单词窗口位置
		var x = event.pageX;
  		var ox = document.body.offsetWidth;
  		if (x > 200 && ox - x < 250) {
    		x -= 200;
  		}

  		var y = event.pageY;
  		var oy = document.body.offsetHeight;

  		//TODO 垂直不能超过页面下方
  		/*if(y + 300 > oy) {
  			y -= 200 - ( oy - y );
  			x += 20;
  		}*/

  		RESULT_DIV_LEFT = x;
  		RESULT_DIV_TOP = y;

  		//alert("x:"+x+", y:"+y+", width:"+document.querySelectorAll(resultDivSelector)[0].offsetWidth);
}

function getValidSelection(){
	if(!isMouseOnResultDiv){
		document.querySelectorAll(resultDivSelector)[0].style.display = "none";
		document.querySelectorAll(resultDivSelector)[0].textContent = ""; // 每次重新取值时清空单词信息
	}

	var text = wQueryforsb.trim(String(window.getSelection()));
	var pattern = /^[a-zA-Z]+$/;
	if(pattern.test(text)){
		return text;
	}else{
		return;
	}
}


function initResultDiv() {
	var resultDiv = document.createElement("div");
	resultDiv.id = resultDivId;
	resultDiv.className = resultDivClassName;

	// 鼠标在查询结果内时，点击事件不重新查词或导致结果消失
	resultDiv.addEventListener("mouseover", function() {
		isMouseOnResultDiv = true;
	});
	resultDiv.addEventListener("mouseout", function() {
		isMouseOnResultDiv = false;
	});

	document.querySelectorAll("body")[0].appendChild(resultDiv);

	addCSS();
}

function addCSS(){
	//var reader = new FileReader();
	//reader.readAsText();

	var style = document.createElement("style");
	style.type = "text/css";
	//$(style).load("css/resultDiv.css");
	style.innerHTML = "#addworda {display:inline-block;}.addworda{padding-left: 10px;} .mxShanbayDefinitionDiv {margin-top: 10px;}.mxShanbayResultDiv {z-index: 3000000000;text-align: left;position: absolute;width: 200px;border-radius: 4px;margin: 20px auto;display: none;padding:20px;background: #D4DEDF;box-shadow: 0 1px 2px rgba(34, 25, 25, 0.4);background: -webkit-linear-gradient(90deg, #D4DEDF, #DCDCDE);}.wordDiv {}.mxShanbayResultDiv a {color:blue;text-decoration:none;}";
	document.head.appendChild(style);
	//$("head").append(style);
}

function wordQuery(word){
	if(isMouseOnResultDiv){
		return;
	}

	wQueryforsb.get(WORD_QUERY_API+word, null, function(data) {
		if(data.voc.conent_id == null){
			return;
		}

		var storage = new Object();// = runtime.storage;
		storage.word = word;
		storage.definition = data.voc.definition;
		storage.pron = data.voc.pron;
		storage.learning_id = data.learning_id;
		storage.conent_id = data.voc.conent_id;
		storage.us_audio = data.voc.us_audio;
		storage.uk_audio = data.voc.uk_audio;

		showWord(storage);
	}, "json");
}

function showWord(storage){

	var wordDiv = document.createElement("div");
	wordDiv.id = WORD_DIV_ID;
	wordDiv.className = WORD_DIV_ID;
	wordDiv.innerHTML=storage.word+"["+storage.pron+"]";

	document.querySelectorAll(resultDivSelector)[0].appendChild(wordDiv);

	//document.querySelectorAll(WORD_DIV_SELECTOR).appendChild(storage.word+"["+storage.pron+"]");
	


	// 判断是否已经添加过此单词
	if(storage.learning_id == 0){
		var operationDiv = document.createElement("div");
		operationDiv.id = ADD_WORD_OPERA_DIV_ID;
		operationDiv.className = ADD_WORD_OPERA_DIV_ID;
		document.querySelectorAll(WORD_DIV_SELECTOR)[0].appendChild(operationDiv);

		var operation  = document.createElement("a");
		operation.href = "javascript:void();";
		operation.addEventListener("click", addword, false);
		operation.innerHTML = "[添加]";
		document.querySelectorAll(ADD_WORD_OPERA_SELECTOR)[0].appendChild(operation);
		//$(ADD_WORD_OPERA_SELECTOR).append("[添加]");
	}else{
		//TODO 代码重复
		var operation = document.createElement("span");
		operation.id = ADDED_WORD_SPAN_ID;
		operation.className = ADDED_WORD_SPAN_ID;
		operation.innerHTML = "[已添加]";
		document.querySelectorAll(WORD_DIV_SELECTOR)[0].appendChild(operation);
		//$(ADDED_WORD_SPAN_SELECTOR).append("[已添加]");
	}
	
	var pronunciation = document.createElement("div");
	pronunciation.id = PRONUNCIATION_DIV_ID;
	document.querySelectorAll(WORD_DIV_SELECTOR)[0].appendChild(pronunciation);

	var audio = document.createElement("audio");
	document.querySelectorAll(PRONUNCIATION_DIV_SELECTOR)[0].appendChild(audio);
	
	var uk_a = document.createElement("a");
	uk_a.href = "javascript:void();";
	uk_a.innerHTML = "[英音]";
	uk_a.addEventListener("click", function(){
		audio.preload="auto";
		audio.src = storage.uk_audio;
		audio.play();
	}, false);
	document.querySelectorAll(PRONUNCIATION_DIV_SELECTOR)[0].appendChild(uk_a);
	
	var us_a = document.createElement("a");
	us_a.href = "javascript:void();";
	us_a.innerHTML = "[美音]";
	us_a.addEventListener("click", function(){
		audio.preload="auto";
		audio.src = storage.us_audio;
		audio.play();
	}, false);
	document.querySelectorAll(PRONUNCIATION_DIV_SELECTOR)[0].appendChild(us_a);

	var definition = document.createElement("div");
	definition.id = DEFINITION_DIV_ID;
	definition.className = DEFINITION_DIV_ID;
	definition.innerHTML = nToBr(storage.definition);
	document.querySelectorAll(resultDivSelector)[0].appendChild(definition);
	//$(DEFINITION_DIV_SELECTOR).append(nToBr(storage.definition));



  	//$(resultDivSelector).css("left",RESULT_DIV_LEFT+"px");
  	//$(resultDivSelector).css("top",RESULT_DIV_TOP+"px");
  	document.querySelectorAll(resultDivSelector)[0].style.left = RESULT_DIV_LEFT+"px";
  	document.querySelectorAll(resultDivSelector)[0].style.top = RESULT_DIV_TOP+"px";
	document.querySelectorAll(resultDivSelector)[0].style.display = "block";
}

function nToBr(text){
	while(text.indexOf("\n") >= 0) {
		text = text.replace(/\n/, "<br/>");
	}
	return text;
}

function addword() {
	wQueryforsb.get(WORD_ADD_API+WORDNOW, null, function(data) {
		if(data.id != 0 && (typeof data.id != "undefinde")) {
			addedWord();
		}
	}, "json");
}

function addedWord() {
	document.querySelectorAll(ADD_WORD_OPERA_SELECTOR)[0].textContent = "[已添加]";

	//TODO 代码重复
	//var operation = document.createElement("span");
	//operation.id = ADDED_WORD_SPAN_ID;
	//operation.className = ADDED_WORD_SPAN_ID;
	//operation.innerHTML = "[已添加]";
	//document.querySelectorAll(WORD_DIV_SELECTOR)[0].appendChild(operation);
}

runtime.listen("openStatus", function(isopen) {
	var storage = runtime.storage;
	storage.setConfig("isopen", isopen);
	ISOPEN = isopen;
});




	initResultDiv();
	document.querySelectorAll("html")[0].addEventListener("mouseup", function(even) {
		if(!ISOPEN) {
			return;
		}
		var text = getValidSelection();
		if(text != null){
			WORDNOW = text;
			wordQuery(text);
			calculateResultDivSite(even);
			
		}
	}, false);

	var storage = runtime.storage;
    var isopen = storage.getConfig("isopen");
    if(isopen == "true") {
        ISOPEN = true;
    }else{
        ISOPEN = false;
    }
